//
//  NSString+MarsBase64.m
//  WKWebDemo
//
//  Created by yangpenghua on 2018/3/27.
//  Copyright © 2018年 linzi. All rights reserved.
//

#import "NSString+MarsBase64.h"
#import "NSData+MarsBase64.h"

@implementation NSString (MarsBase64)
+ (NSString *)mars_stringWithBase64EncodedString:(NSString *)string
{
    NSData *data = [NSData mars_dataWithBase64EncodedString:string];
    if (data)
    {
        return [[self alloc] initWithData:data encoding:NSUTF8StringEncoding];
    }
    return nil;
}
- (NSString *)mars_base64EncodedStringWithWrapWidth:(NSUInteger)wrapWidth
{
    NSData *data = [self dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:YES];
    return [data mars_base64EncodedStringWithWrapWidth:wrapWidth];
}
- (NSString *)mars_base64EncodedString
{
    NSData *data = [self dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:YES];
    return [data mars_base64EncodedString];
}
- (NSString *)mars_base64DecodedString
{
    return [NSString mars_stringWithBase64EncodedString:self];
}
- (NSData *)mars_base64DecodedData
{
    return [NSData mars_dataWithBase64EncodedString:self];
}

#pragma - 将saveBase64编码中的"-"，"_"字符串转换成"+"，"/"，字符串长度余4倍的位补"="
+ (NSData*)mars_safeUrlBase64Decode:(NSString*)safeUrlbase64Str
{
    // '-' -> '+'
    // '_' -> '/'
    // 不足4倍长度，补'='
    NSMutableString * base64Str = [[NSMutableString alloc]initWithString:safeUrlbase64Str];
    base64Str = (NSMutableString * )[base64Str stringByReplacingOccurrencesOfString:@"-" withString:@"+"];
    base64Str = (NSMutableString * )[base64Str stringByReplacingOccurrencesOfString:@"_" withString:@"/"];
    NSInteger mod4 = base64Str.length % 4;
    if(mod4 > 0) {
        [base64Str appendString:[@"====" substringToIndex:(4-mod4)]];
    }
    return  [NSData mars_dataWithBase64EncodedString:base64Str];
    
}

#pragma - 因为Base64编码中包含有+,/,=这些不安全的URL字符串，所以要进行换字符
+ (NSString*)mars_safeUrlBase64Encode:(NSData*)data
{
    NSString * base64Str = [data mars_base64EncodedString];
    NSMutableString * safeBase64Str = [[NSMutableString alloc]initWithString:base64Str];
    safeBase64Str = (NSMutableString * )[safeBase64Str stringByReplacingOccurrencesOfString:@"+" withString:@"-"];
    safeBase64Str = (NSMutableString * )[safeBase64Str stringByReplacingOccurrencesOfString:@"/" withString:@"_"];
    safeBase64Str = (NSMutableString * )[safeBase64Str stringByReplacingOccurrencesOfString:@"=" withString:@""];
    return safeBase64Str;
}

@end
